//
//  PPPetInfpTableViewController.m
//  pet
//
//  Created by 陈无忌 on 11/20/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPPetInfoTableViewController.h"
#import "PPPetPhotoCollectionViewCell.h"
#import "supportingHeadFiles.h"
#import "PPPreviewPetPhotoViewController.h"
//#import "PPSystemConfiguraton.h"

@interface PPPetInfoTableViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *ageLabel;
@property (weak, nonatomic) IBOutlet UIImageView *sexImageView;
@property (weak, nonatomic) IBOutlet UILabel *breedLabel;
@property (weak, nonatomic) IBOutlet UILabel *breedingLabel;
@property (weak, nonatomic) IBOutlet UILabel *lengthLabel;
@property (weak, nonatomic) IBOutlet UILabel *weigthLabel;
@property (weak, nonatomic) IBOutlet UILabel *colorLabel;
@property (weak, nonatomic) IBOutlet UILabel *petPhotoLabel;
@property (weak, nonatomic) IBOutlet UICollectionView *petPhotoCollectionView;

@property (weak, nonatomic) IBOutlet UILabel *introductionLabel;
@property (nonatomic) CGFloat introductionHeight;

@end

@implementation PPPetInfoTableViewController

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}


- (void)viewReload
{
    self.petPhotoCollectionView.dataSource = self;
    self.petPhotoCollectionView.delegate = self;
    
    
    
    
    if (self.pet) {
        [self.tableView setHidden:NO];
        self.nameLabel.text = self.pet.petName;
        if (self.pet.birth) {
            self.ageLabel.text = self.pet.birth;
        }else{
            self.ageLabel.text = @"未设置";
        }
        
        self.breedLabel.text = [NSString stringWithFormat:@"%@",self.pet.petBreed];
        if ([self.pet.breeding isEqualToString:@"yes"]) {
            self.breedingLabel.text = @"需要";
            self.petPhotoLabel.hidden = NO;
            self.petPhotoCollectionView.hidden = NO;
        }else{
            self.breedingLabel.text = @"不需要";
            self.petPhotoLabel.hidden = YES;
            self.petPhotoCollectionView.hidden = YES;
        }
        switch (self.pet.petGender) {
            case 0:
                [self.sexImageView setImage:[UIImage imageNamed:@"male"]];
                break;
            case 1:
                [self.sexImageView setImage:[UIImage imageNamed:@"female"]];
                break;
            default:
                break;
        }
        if (self.pet.petLong) {
            self.lengthLabel.text = [NSString stringWithFormat:@"%.2f",self.pet.petLong];
        }else{
            self.lengthLabel.text = @"未设置";
        }
        
        if (self.pet.weight) {
            self.weigthLabel.text = [NSString stringWithFormat:@"%.2f",self.pet.weight];
        }else{
            self.weigthLabel.text = @"未设置";
        }
        
        if (self.pet.color.length > 0 && self.pet.color) {
            self.colorLabel.text = self.pet.color;
        }else{
            self.colorLabel.text = @"未设置";
        }
        self.introductionLabel.frame = CGRectMake(19, 36, 282, 15);
        if (self.pet.introduction.length > 0) {
            self.introductionLabel.text = self.pet.introduction;
        }else{
            self.introductionLabel.text = @"主人很懒，什么都没写...";
        }
        self.introductionLabel.numberOfLines = 0;
        self.introductionLabel.lineBreakMode = NSLineBreakByCharWrapping;
        [self.introductionLabel sizeToFit];
        self.introductionHeight = 36 + self.introductionLabel.frame.size.height + 10;
        
        
        [self.tableView reloadData];
        [self.petPhotoCollectionView reloadData];
    }else{
        [self.tableView setHidden:YES];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Collection view data source
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.pet.petImgList.count > 0) {
        if (self.pet.petImgList.count < 3) {
            return self.pet.petImgList.count;
        }else{
            return 3;
        }
    }else{
        return 0;
    }
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PPPetPhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"petPhotoCell" forIndexPath:indexPath];
    PPPetPhoto *photo = [self.pet.petImgList objectAtIndex:indexPath.row];
    [cell.photoView setImageWithURL:[PPImageUrl getImageUrl:photo.img] placeholderImage:[UIImage imageNamed:@"defaultImage"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [cell.photoView setContentMode:UIViewContentModeScaleAspectFill];
    [cell.photoView setClipsToBounds:YES];

    return cell;
}


#pragma mark - Table view delegate

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 5) {
        if ([self.pet.breeding isEqualToString:@"yes"]) {
            return 70;
        }else{
            return 0;
        }
    }else if (indexPath.row == 6){
        return self.introductionHeight;
    }else{
        return 44;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 5){
        PPPreviewPetPhotoViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPPreviewPetPhotoViewController"];
        targetVC.pet = self.pet;
        [self.navigationController pushViewController:targetVC animated:YES];
    }
}


#pragma mark - Custom IBAction
- (IBAction)deletePet:(id)sender {
    [UIAlertView showWithTitle:@"放生" message:@"确定要放了它么？" cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            [self deleteThePet:self.pet];
        }
    }];
}

- (void)deleteThePet:(PPPetInfo *)pet
{
    NSString *url = [PPAPIList getAPIList].PPDeletePetById;
    NSDictionary *params =@{@"userId":@(self.pet.userId),
                            @"petId":@(self.pet.id),
                            };
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
        NSLog(@"%@",responseObject);
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.integerValue == 1) {
            [UIAlertView showWithTitle:@"再见了" message:@"成功放归大自然！" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"petListRelod" object:nil];
            }];
        } else {
            [UIAlertView showWithTitle:@"宠物不想走" message:@"放归大自然失败，请稍后再试" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:nil];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error){
        [UIAlertView showWithTitle:@"提示" message:@"网络不给力" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:nil];
    }];
}


/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
